import requests
import json
import re
import time
import os
from PIL import Image
import cv2

import settings
from common import VideoType

"""
获取违禁词信息
"""


def download_video(url, name, path):
    """
    下载视频文件
    :param url: 视频文件路径
    :param name: 文件名称
    :param path: 文件目录
    :return: true or false
    """

    try:
        video_path = os.path.join(path, name + ".mp4")
        if os.path.isfile(video_path):
            return os.path.abspath(video_path)
        headers = {
            "Connection": "close",
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, "
                          "like Gecko) Version/11.0 Mobile/15A372 Safari/604.1 "
        }
        video = requests.get(url=url, headers=headers, timeout=20)
        with open(video_path, 'wb') as file:
            file.write(video.content)
            file.close()
        return os.path.abspath(video_path)
    except BaseException as e:
        raise RuntimeError("下载视频失败: " + str(e))


def cookie_str_to_dict(cookies):
    """
    将字符串 cookie 转换成字典 cookie
    :param cookies: cookie str
    :return: cookie dict
    """
    cookies = json.loads(cookies)

    ck = ""
    if len(cookies) > 0:
        for i in cookies:
            ck = ck + i["name"] + "=" + i["value"] + ";"

    return ck


def judge_cookie_is_pass(cookies):
    """
    判断cookie是否可用, 可用返回  token, 不可用返回 抛出异常
    :param cookies: cookie str
    :return:
    """
    _cookie = cookie_str_to_dict(cookies)
    headers = {
        "cookie": _cookie
    }
    response = requests.get(url="https://baijiahao.baidu.com/builder/app/appinfo?", headers=headers, timeout=20)
    try:
        result = response.json()
        if result['data']['user']["cms_pc_show_status"] == "封禁":
            raise RuntimeError("已封禁")
        if result["errno"] == 0:
            token = response.headers["token"]
            return token
        else:
            raise RuntimeError("cookie 不可用")
    except:
        raise RuntimeError("获取 token 时,返 不是 json, content: " + response.text)


def get_video_type(path: str) -> VideoType:
    """
    返回视频是横版还是竖版
    :param path: 视频路径
    :return: string: 'Horizon' or 'Vertical'
    """
    img_type = VideoType.HORIZONTAL
    cap = cv2.VideoCapture(path)
    width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
    height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
    if height > width:
        img_type = VideoType.VERTICAL
    return img_type


def cut_img(img_path):
    """
        图片处理
    :param img_path: 图片路径
    :return: boolean
    """
    im = Image.open(img_path)
    x, y = im.size  # read image size

    if x >= y:
        x_s = 850
    else:
        x_s = 720

    y_s = y * x_s / x  # calc height based on standard width
    y_s = int(y_s)
    out = im.resize((x_s, y_s), Image.ANTIALIAS)  # resize image with high-quality
    out.save(img_path)


def download_pic(url, name, path=settings.DOWNLOAD_CACHE_DIR):
    """
    下载图片
    :param url: 图片下载 url
    :param name: 图片名称
    :param path:  图片保存路径
    """
    headers = {
        "Connection": "close",
        "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, "
                      "like Gecko) Version/11.0 Mobile/15A372 Safari/604.1 "
    }
    if "http" not in url:
        url = "http:" + url

    suffix = get_suffix(url)
    pic = requests.get(url=url, headers=headers, timeout=10)
    path = os.path.join(path, name + "." + suffix)
    with open(path, 'wb') as file:
        file.write(pic.content)
        file.close()
    return os.path.abspath(path)


def rewrite(status, content_id, reason=''):
    """
    报告信息
    :param status:  状态 3 成功, 4 失败
    :param content_id:  id
    :param reason: 原因
    :return:
    """
    data = {
        "content_id": content_id,
        "status": status,
        "reason": reason
    }
    requests.post(url="http://www.nvhuangchina.cn/api/article/baijia/write", data=data)


def get_real_download_url(article):
    """
    获取视频的真实下载路径, 有 10 次重试机会
    :param article: 文章
    :return: 真实下载路径
    """
    url = article["url"]
    if article['platform'] in ("ks", "taobao", "tb"):
        return url

    prefix = ""
    if article['platform'] == "douyin":
        prefix = "https://www.douyin.com/video/"

    if article['platform'] == "oasis":
        prefix = "https://m.oasis.weibo.cn/v1/h5/share?sid="

    if article['platform'] in ("xiaohongshu", "xhs"):
        prefix = "https://www.xiaohongshu.com/discovery/item/"

    if article['platform'] == "bilibili":
        prefix = "https://www.bilibili.com/video/"

    if article['platform'] == "xg":
        prefix = "https://www.ixigua.com/"

    if article['platform'] == "wyy":
        prefix = "https://st.music.163.com/mlog/mlog.html?id="
    for i in range(10):
        url = 'http://www.nvhuangchina.cn/api/xhs/getRealUrl'
        api_url = url + '?url=' + prefix + str(article["content_id"])
        try:
            res = requests.get(url=api_url, timeout=12)
        except:
            time.sleep(2)
            continue
        try:
            result = res.json()
        except:
            raise RuntimeError("获取视频真实地址时, 返回的不是 json, content: ", res.text)
        if result["result"] is None or result["result"] == "":
            time.sleep(3)
            continue
        ret = result['result']
        break
    else:
        raise RuntimeError("获取视频真实地址失败")
    return ret


def create_dir(article_id):
    """
    给具体发布的每一条文章创建缓存目录
    :param article_id:
    :return:
    """
    is_exists = os.path.exists(settings.DOWNLOAD_CACHE_DIR)
    if not is_exists:
        os.makedirs(settings.DOWNLOAD_CACHE_DIR)

    article_dir = os.path.join(settings.DOWNLOAD_CACHE_DIR, str(article_id))
    if not os.path.exists(article_dir):
        os.makedirs(article_dir)
    return article_dir


def filter_str(desstr, restr=''):
    """
    过滤除中英文及数字以外的其他字符
    :param desstr:
    :param restr:
    :return:
    """
    res = re.compile(u'[\U00010000-\U0010ffff\\uD800-\\uDBFF\\uDC00-\\uDFFF]')
    return res.sub(restr, desstr)


def find_emoji(restr=''):
    """
    过滤除中英文及数字以外的其他字符
    :param restr:
    :return:
    """
    res = re.compile(u'[\U00010000-\U0010ffff\\uD800-\\uDBFF\\uDC00-\\uDFFF]')
    flag = re.findall(res, restr)
    if len(flag) > 0:
        raise RuntimeError("内容中包含表情")


# 违禁词汇全局变量
prohibited_words = []


def contains_prohibited_word(content):
    global prohibited_words
    if len(prohibited_words) == 0:
        words = prohibited_words
    else:
        response = requests.get("http://www.nvhuangchina.cn/api/xhs/wjch", timeout=20)
        try:
            res = response.json()
        except ValueError:
            raise RuntimeError("获取违禁词 json 失败, content: ", response.text)
        prohibited_words = words = res["result"]
    for i in words:
        if i in str(content):
            raise RuntimeError("内容出现违规词汇:" + str(contains_prohibited_word))


def get_suffix(url):
    """
    获取 url 代表的资源的类型
    :param url: url str
    :return: str
    """
    data = requests.get(url, timeout=10).headers
    data_type = data['Content-Type']
    if "png" in data_type:
        return "png"
    else:
        return "jpg"


def file_size(path):
    """
    获取文件大小
    :param path: 文件路径
    :return: 文件大小单位是 MB
    """
    return os.stat(path).st_size / (1024 * 1024)


def judge_account_can_publish(cookies, token, video_type: VideoType):
    """
    判断当前账号是否还能继续发文
    :param cookies: cookie str
    :param token: token str
    :param video_type: 是横版视频还是竖版视频
    :return:
    """
    _cookie = cookie_str_to_dict(cookies)
    headers = {
        "cookie": _cookie,
        "token": token
    }

    try:
        response = requests.get(url="https://baijiahao.baidu.com/pcui/article/edit?type=ugc_video", headers=headers,
                                timeout=12)
        result = response.json()
        if video_type == VideoType.HORIZONTAL:
            if result['data']['ability']["publish_number"]["video"] == 0:
                raise RuntimeError(settings.FEEDBACK.ACCOUNT.HORIZONTAL_ZERO)
        if video_type == VideoType.VERTICAL:
            if result['data']['ability']["publish_number"]["ugc_video"] == 0:
                raise RuntimeError(settings.FEEDBACK.ACCOUNT.VERTICAL_ZERO)

    except:
        raise RuntimeError("judge_account_can_publish_exception")

if __name__ == '__main__':
    cookie = "[{\"domain\":\".baidu.com\",\"hostOnly\":false,\"httpOnly\":false,\"name\":\"BAIDUID\",\"path\":\"/\",\"sameSite\":\"no_restriction\",\"secure\":false,\"session\":true,\"storeId\":\"0\",\"value\":\"F49E89A7DEC8D6EC28F15A8F8FEDDB97:FG=1\"},{\"domain\":\".baijiahao.baidu.com\",\"hostOnly\":false,\"httpOnly\":false,\"name\":\"PHPSESSID\",\"path\":\"/\",\"sameSite\":\"no_restriction\",\"secure\":false,\"session\":true,\"storeId\":\"0\",\"value\":\"49a4860jij6u3abcpck58phph1\"},{\"domain\":\".baijiahao.baidu.com\",\"hostOnly\":false,\"httpOnly\":false,\"name\":\"canary\",\"path\":\"/\",\"sameSite\":\"no_restriction\",\"secure\":false,\"session\":true,\"storeId\":\"0\",\"value\":\"0\"},{\"domain\":\".baijiahao.baidu.com\",\"hostOnly\":false,\"httpOnly\":false,\"name\":\"gray\",\"path\":\"/\",\"sameSite\":\"no_restriction\",\"secure\":false,\"session\":true,\"storeId\":\"0\",\"value\":\"0\"},{\"domain\":\".baidu.com\",\"hostOnly\":false,\"httpOnly\":true,\"name\":\"__yjs_duid\",\"path\":\"/\",\"sameSite\":\"no_restriction\",\"secure\":true,\"session\":true,\"storeId\":\"0\",\"value\":\"1_3affb05e4fff2ac94ecef9d365bdb4961614257883293\"},{\"domain\":\".baidu.com\",\"expirationDate\":1896446971.782588,\"hostOnly\":false,\"httpOnly\":true,\"name\":\"BDUSS\",\"path\":\"/\",\"sameSite\":\"no_restriction\",\"secure\":false,\"session\":false,\"storeId\":\"0\",\"value\":\"lp2b0pnWTM1elRGRmR3MVQyMnpXSEItNmtFVjN6YksxQkY5bDhEcEZoWDc5TDFoRVFBQUFBJCQAAAAAAAAAAAEAAAAY~LlazrPNurO30L20xgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPtnlmH7Z5ZhV\"},{\"domain\":\".baidu.com\",\"expirationDate\":1896446971.782891,\"hostOnly\":false,\"httpOnly\":true,\"name\":\"BDUSS_BFESS\",\"path\":\"/\",\"sameSite\":\"no_restriction\",\"secure\":true,\"session\":false,\"storeId\":\"0\",\"value\":\"lp2b0pnWTM1elRGRmR3MVQyMnpXSEItNmtFVjN6YksxQkY5bDhEcEZoWDc5TDFoRVFBQUFBJCQAAAAAAAAAAAEAAAAY~LlazrPNurO30L20xgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPtnlmH7Z5ZhV\"},{\"domain\":\"baijiahao.baidu.com\",\"hostOnly\":true,\"httpOnly\":false,\"name\":\"RECENT_LOGIN\",\"path\":\"/\",\"sameSite\":\"no_restriction\",\"secure\":false,\"session\":true,\"storeId\":\"0\",\"value\":\"1\"},{\"domain\":\"baijiahao.baidu.com\",\"expirationDate\":1668782976.758538,\"hostOnly\":true,\"httpOnly\":false,\"name\":\"canary\",\"path\":\"/\",\"sameSite\":\"no_restriction\",\"secure\":false,\"session\":false,\"storeId\":\"0\",\"value\":\"0\"},{\"domain\":\"baijiahao.baidu.com\",\"expirationDate\":1668782976.758595,\"hostOnly\":true,\"httpOnly\":false,\"name\":\"gray\",\"path\":\"/\",\"sameSite\":\"no_restriction\",\"secure\":false,\"session\":false,\"storeId\":\"0\",\"value\":\"1\"},{\"domain\":\".baijiahao.baidu.com\",\"expirationDate\":1668782974,\"hostOnly\":false,\"httpOnly\":false,\"name\":\"Hm_lvt_f7b8c775c6c8b6a716a75df506fb72df\",\"path\":\"/\",\"sameSite\":\"no_restriction\",\"secure\":false,\"session\":false,\"storeId\":\"0\",\"value\":\"1637246974\"},{\"domain\":\".baijiahao.baidu.com\",\"hostOnly\":false,\"httpOnly\":false,\"name\":\"Hm_lpvt_f7b8c775c6c8b6a716a75df506fb72df\",\"path\":\"/\",\"sameSite\":\"no_restriction\",\"secure\":false,\"session\":true,\"storeId\":\"0\",\"value\":\"1637246974\"},{\"domain\":\".baijiahao.baidu.com\",\"expirationDate\":1642430977.053955,\"hostOnly\":false,\"httpOnly\":true,\"name\":\"devStoken\",\"path\":\"/\",\"sameSite\":\"no_restriction\",\"secure\":false,\"session\":false,\"storeId\":\"0\",\"value\":\"5e6fe78fef5b0bcbc773518529717b48adf59646c258108b5685f56642d8c92b\"},{\"domain\":\".baijiahao.baidu.com\",\"expirationDate\":1642430977.054015,\"hostOnly\":false,\"httpOnly\":true,\"name\":\"bjhStoken\",\"path\":\"/\",\"sameSite\":\"no_restriction\",\"secure\":false,\"session\":false,\"storeId\":\"0\",\"value\":\"e6079da3e28202f9f29343f370ebcac5adf59646c258108b5685f56642d8c92b\"},{\"domain\":\".baidu.com\",\"expirationDate\":1637254177.672645,\"hostOnly\":false,\"httpOnly\":true,\"name\":\"ab_sr\",\"path\":\"/\",\"sameSite\":\"no_restriction\",\"secure\":true,\"session\":false,\"storeId\":\"0\",\"value\":\"1.0.1_YmM5ZWFkYTc3ZWUzNmQ0NmI2NTkxMjQ0MTYxNTUxOTM5ODUyMzE0ZTIwYTYxZmRlODViMzM1M2M2OWUzMjBjMzE1ODUwNWIzY2ZmNWQ1YTg1ZDlhMjU0ODRmNmI0NThiZjkyYjQyOWQ5NjM2YjhjNmRiYzk4NjNjMTM5MzAxY2U0ZmVjNTFiNjEwOWE5MDYwMzE3MDdiZmE3NDYxZDAzNA==\"},{\"domain\":\".baidu.com\",\"expirationDate\":1637851779,\"hostOnly\":false,\"httpOnly\":false,\"name\":\"RT\",\"path\":\"/\",\"sameSite\":\"no_restriction\",\"secure\":false,\"session\":false,\"storeId\":\"0\",\"value\":\"\\\"sl=2&ss=kw52kq96&tt=5h6&bcn=https%3A%2F%2Ffclog.baidu.com%2Flog%2Fweirwood%3Ftype%3Dperf&z=1&dm=baidu.com&si=935mkizjrgk&ld=45s\\\"\"}]"
    judge_cookie_is_pass(cookie)
